#include<memory>
#include<vector>
#include"UdpServer.hpp"
#include"Log.hpp"

void Usage(std::string proc)
{
    std::cout<<"\n\rUsage:"<<proc<<" port[1024+]"<<std::endl;
}

std::string Handler(const std::string& str,uint16_t clientport,const std::string& clientip)
{
    std::cout<<"["<<clientip<<":"<<clientport<<"]"<<std::endl;
    std::string res = "Server get a message";
    res += str;
    std::cout<<res<<std::endl;
    return res;
}

bool SafeCheck(const std::string& cmd)
{
    int safe = false;
    std::vector<std::string> key_word = {"rm","mv","cp","kill","sudo","unlink","yum","top"};
    for(auto& word:key_word)
    {
        auto pos = cmd.find(word);
        if(pos != std::string::npos)
        {
            safe == false;
        }
    }
    return true;
}

std::string ExcuteCommand(const std::string& cmd)
{

    if(!SafeCheck(cmd))
    {
        return "false";
    }
    FILE* fp = popen(cmd.c_str(),"r");
    if(nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while(true)
    {
        char* res = fgets(buffer,sizeof(buffer),fp);
        if(res == nullptr)
        {
            break;
        }
        result += buffer;
        std::cout<<result<<std::endl;
    }
    pclose(fp);
    return result;
}

int main(int argc,char* argv[])
{   
    if(argc!=2)
    {
        Usage(argv[0]);
        exit(0);
    }
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<UdpServer> svr(new UdpServer(port,"127.0.0.1"));//测试接口"127.0.0.1"

    svr->Init();
    svr->Run();//Handler);

    return 0;
}